/*
 * 2008 - 2009 Copyright (C) Ciprian Docan <docan@cac.rutgers.edu>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 */

#include <stdio.h>
#include <unistd.h>

extern int etext, edata, end;

static int ivar = 10;
static int iarr[20];

static void function_foo()
{
}

static void function_bar()
{
}


void localize_address_in_segment( void *addr, char *sym )
{
        unsigned int addr_text = (unsigned int) &etext;
        unsigned int addr_init_data = (unsigned int) &edata;
        unsigned int addr_noinit_data = (unsigned int) &end;
        unsigned int addr_any = (unsigned int) addr;

        if( addr_any <= addr_text ) 
                printf( "%s address 0x%x is in the .text segment\n",
                        sym, addr_any );
        else if( addr_any <= addr_init_data ) 
                printf( "%s address 0x%x is in the .init_data segment\n", 
                        sym, addr_any );
        else if( addr_any <= addr_noinit_data )
                printf( "%s address 0x%x might be in the .uinit_data"
                        " segment\n", sym, addr_any );
        else
                printf( "%s I can not locate address 0x%x \n", sym, addr_any );
}


int main( void )
{
        int  i;
        void *addr[] = { &ivar, &iarr, &function_foo, &function_bar, &i, &main  };
        char *syms[] = { "ivar", "iarr", "foo", "bar", "i", "main" };

        printf( ".text segment starts at 0x%x\n"
                ".init data segment starts at 0x%x\n"
                ".unint data segment starts at 0x%x\n",
                (unsigned int) &etext, (unsigned int) &edata, 
                (unsigned int) &end );


        for( i = 0; i < sizeof(addr)/sizeof(addr[0]); i++ )
                localize_address_in_segment( addr[i], syms[i] );
        /* sleep( 60 ); */


        return 0;
}
